"ui";

// 文档地址 http://doc.autoxjs.com/#/

ui.layout(
    <vertical padding="20">
        <horizontal gravity="left|center">
            <text textColor="#000000" textSize="15">刷新滴滴：</text>
            <checkbox id="freshDidi" />
        </horizontal>

        <horizontal gravity="left|center">
            <text w="auto" textColor="#000000" textSize="15">刷新间隔:</text>
            <input w="auto" id="freshTime" inputType="number" text="4" hint="刷新间隔" />
            <text w="*" textColor="#000000" textSize="15">秒</text>
        </horizontal>

        <horizontal gravity="left|center">
            <text w="auto" textColor="#000000" textSize="15">浮窗位置:</text>
            <input w="auto" id="position" inputType="number" text="4" hint="刷新间隔" />
        </horizontal>


        <button id="startBtn" text="启动APP"/>
        <button id="pauseBtn" text="暂停" />
    </vertical>
);

/* 绑定按钮点击事件 */
ui.pauseBtn.click(setRunOrStop)
ui.startBtn.click(() => {
    try{

        if (freshTimer) {
            clearInterval(freshTimer)
        }
    }catch(e){
        log(e)
    }
    
    runApp()
})


/* =============================浮窗 BEGIN ========================== */
/* 1.定义浮窗UI */
var floatyWin = floaty.window(
    <frame gravity="center_vertical|center_horizontal"    padding="0">
        <button  id="runBtn" padding="0" margin="0" style="Widget.AppCompat.Button.Colored" text="停"/>
    </frame>
)   
/* 2.浮窗位置 */
floatyWin.setPosition(900, 1200)  //设置初始位置
floatyWin.setAdjustEnabled(true)  //允许可拖动
floatyWin.exitOnClose()           //关闭退出脚本
/* 3.绑定浮窗按钮事件 */
floatyWin.runBtn.click(function() {
    ui.run(setRunOrStop)
})

/* 4.绑定浮窗拖动事件 */
var currentX = floatyWin.getX(); // 浮窗的当前位置
var currentY = floatyWin.getY();
var touchStartX, touchStartY; // 触摸事件的初始位置
var isDragging = false; // 是否正在拖动浮窗

/* =============================浮窗 END============================ */

// var tools = require('./tools.js')
var tools = {
    playMusic: function() {
        media.playMusic("/sdcard/Download/WeiXin/music.mp3");
        let timer = setInterval(() => {clearInterval(timer)}, media.getMusicDuration())
    },
    playLongMusic: function() {
        media.playMusic("/sdcard/Download/WeiXin/ningsheng.mp3");
        setTimeout(()=> {}, media.getMusicDuration())
    }
}

/**改变刷新状态 */
function setRunOrStop() {
    freshRunning = !freshRunning
    ui.pauseBtn.setText(freshRunning ? "暂停" : "恢复运行")
    floatyWin.runBtn.setText(freshRunning ? '停' : '刷')
    let appName = currentPackage()
    if (freshRunning &&  appName != hello.appName && appName != didi.appName) {
        home()
        launchApp("哈啰")
    }
}

/**函数库**/
function log(msg) {console.log(msg)}

var samePathProgress = 80 // 自动接单顺路度
var freshDidi = false // 是否刷新Didi
var freshTime = 4000  // 刷新间隔时间
var freshTimer = null //刷新定时器
var freshRunning = true // 刷新状态 
var freshIndex = 0

// runApp()
function getSetting() {
    freshDidi = ui.freshDidi.checked
    freshTime = parseInt(ui.freshTime.text()) * 1000
}

setTimeout(() => {
    runApp()
}, 1000)


function runApp() {
    try {
        getSetting()
        home()
    } catch (e) {
        log(e)
        return
    }
    log('启动APP')
    launchApp('哈啰')
    freshTimer = setInterval(loop_fresh, freshTime)
}

function loop_fresh() {
    log("循环刷新")
    if (!freshRunning) 
        return null;
    
    freshIndex = freshIndex + 1

    let appName = currentPackage()
    let page = currentActivity()

    if (appName != didi.appName && appName != hello.appName) {
        // home()
        // launchApp('哈啰')
    }
    
    // 这里的意思是刷新哈啰3次，然后再刷新滴滴1次，刷滴滴的频率比哈啰慢

    // 刷滴滴出行
    if (freshIndex == 4) {
        freshIndex = 0
        if (freshDidi) {
            didi.run()
            return
        }
    }

    // 刷新哈啰出行
    if (freshIndex != 4) { // 哈啰出行    
        // launchApp('哈啰')
        hello.run()
    }
}


var hello = {
    appName: 'com.jingyao.easybike',
    listPage: 'com.hellobike.hitch.business.match.temp.HitchDriverTempMatchActivity',
    passengers: ["", ""],
    run: function() {
        let page = currentActivity()
        if (page == this.listPage) {
            this.freshPassengerAction()
        } else {
            log('当前页面:' + page)
        }
    },
    findMyPathPlan:function () {
        log('进入寻找行程')
        let pathPlan = id('title').findOnce()

        // 如果还没有行程
        if (!pathPlan) {
            return log('还没有发布行程')
        } 

        // 点击行程进入列表页面
        pathPlan.parent().click()
        this.findPassenger()
    },
    /**刷新乘客 */
    freshPassengerAction: function () {
        try {
            log('freshPassengerAction')
            let btnBoxs = id("rcQuickScreen").findOne().children()
            btnBoxs.forEach(child => {
                // 现在采用的刷新机制就是不断的切换是否拼座 实际就是点击拼座这个按钮
                if (child == null) {
                    throw Error('刷新组件不存在')
                }
        
                let target = child.findOne(id("tvText"));
                if(target == null) {
                    log('没有找到刷新按钮') // 离开了当前页面
                    throw Error('没有找到刷新按钮')
                }
                let text = target.text()
                log(text)
                if (text == "独享") {
                    child.click()
                    // 刷新后等待2秒 遍历乘客列表
                    setTimeout(() => { this.findPassenger() }, 1500)
                }
            });
        } catch (error) {
            log(error)
        }
    },
    /**识别顺路乘客 */
    findPassenger: function () {
         // 首先查看是否有顺路单 如果没有的话 再次刷新
    
        // 获取乘客列表
        let passenger = id("tvHitchPercent").findOnce()
        if (passenger == null) { //如果一个乘客都没有 继续刷新
            return
        }

        // 获取顺路度
        let samePath = parseInt(passenger.text())
        log("顺路度" + samePath)

        // 检查是不是新订单
        passenger.parent().parent().parent().find(id("ivNewOrderMark")).forEach(child => {
            if(child) {
                log('新订单')
                tools.playMusic()
            }
        })
        
        let oldAddress = this.passengers[0]
        let newAddress = ''
        try{
            addressInfo = passenger.parent().parent().find(id('tvStartRegionDescribeCross'))
            
            if (addressInfo.length == 0) {
                addressInfo = passenger.parent().parent().find(id('tvStartRegionDescribe'))
            }
            
            addressInfo.forEach(child => {
                newAddress = child.text()  
                log(newAddress)
                this.passengers.push(newAddress)
                this.passengers.splice(0, 1)
            })
        } catch(e) {
            toast('寻找起始地址出错')
            return
        }
    
        if (newAddress == oldAddress) {
            return
        }


        let isSaw = passenger.parent().parent().parent().find(id("ivSaw")).length

        if (samePath >= samePathProgress && !isSaw) {
            // 顺路度比较高 进入订单详情页面接单
            log("点击进入订单详情")
            passenger.parent().parent().parent().click()
            setTimeout(() => { this.robOrder() }, 1000)

        } else if (samePath > 69 && !isSaw) { //新订单并且大于69的顺路度
            tools.playMusic()
            if (freshRunning) {
                freshRunning = false
                setTimeout(() => { freshRunning = true }, 4000)
            }
        }
    },
    /**抢单 */
    robOrder: function() {
        log('进入抢单程序') 
        // 声音提示
        tools.playLongMusic()

        // let note = id('tvTitle').findOne()

        let sureBtn = id('tvButton').findOne()

        if (sureBtn == null) {
            return log('没有找到接单按钮') // 返回列表重新获取
        }

        log('点击抢单')
        sureBtn.click()
    
        setTimeout(() => {
            // 找到确认接单按钮
            let againSureBtn = id("tvPickerSure").findOnce()
            if (againSureBtn) {
                // 当出现提示的时候 系统会要求再次接单
                log('点击确认接单')
                againSureBtn.parent().click()
            }
            this.selectTime()
        }, 300)
    },
    /**选择时间 */
    selectTime: function() {
        let hour = id("hourWheelView").findOnce()
        log(hour)
    
        this.checkRobOrderResult()
    },
    /** 检查抢单结果 */
    checkRobOrderResult: function() {
        let isCancel = id("tvTitle").findOnce()
        log(isCancel)
        // 接单后有三种情况 1.成功 2.乘客已取消 3.已被其他司机接单
        if (isCancel) {
            log(isCancel.text())
        }

        if (isCancel && isCancel.text() == '行程已取消') {
            log('乘客已经取消行程')
            // 这个时候就去寻找其他乘客
        
            let toFindOther = id("tvConfirm").findOnce()
            if (toFindOther) {
                log(toFindOther.text())
            }
            return 
        }
    }
}

var didi = {
    appName: ' com.sdu.didi.psnger',
    listPage: 'com.didi.sdk.app.MainActivity',
    passengers: ["", ""],
    run: function() {
        setTimeout(() => {
            this.freshPassengerAction()
        },500)
    },
    freshNum: 0,
    /**刷新乘客 */
    freshPassengerAction:function() {
        this.freshNum++
        let sortBtn = null
        if (this.freshNum % 2 == 1) {
            sortBtn = id("sfc_drv_wait_sort_button").className("android.widget.TextView").text("智能排序").findOne()
        } else {
            sortBtn = id("sfc_drv_wait_sort_button").className("android.widget.TextView").text("顺路优先").findOne()
        }
        sortBtn.click()

        setTimeout(() => { this.findPassenger() }, 500)
    },
    /** 寻找乘客 */
    findPassenger: function() {
        let firstPassenger = id('sfc_wait_list_item_layout').findOnce()
        if (firstPassenger == null) {
            log('没有找到Didi乘客列表')
            return 
        }
        // log(firstPassenger)
        try{
            firstPassenger.find(id('src_new_order_card_degree_title')).forEach(child => {
                log(child)
            })
        } catch(e) {
            log(e)
        }
        
    }
}